# 1. 导入所需库
import pandas as pd
import numpy as np
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.preprocessing import OneHotEncoder, LabelEncoder
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline

pd.set_option('display.unicode.east_asian_width', True)
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
pd.set_option('max_colwidth', 100)


# 2. 数据加载与基础探索
df = pd.read_csv("takeaway_delivery.csv")
print("数据前5行：\n", df.head())
print("数据形状：", df.shape)
print("描述性统计：\n", df.describe())
# 缺失值与异常值处理
print("缺失值统计：\n", df.isnull().sum())
# （学生补充缺失值处理代码，如df.dropna()或df.fillna()）
df = df.dropna()
print("异常值检查（配送时长<0）：", (df["delivery_time"] < 0).sum())
# （学生补充异常值处理代码，如df = df[df["delivery_time"] >= 0]）

# 3. 数据可视化分析

# 4. 特征工程
# 分类型特征编码（以独热编码为例）
categorical_features = ["is_peak", "weather"]
numeric_features = ["distance", "merchant_rating", "order_amount"]

# 构建预处理管道（避免数据泄露）
preprocessor = ColumnTransformer(
    transformers=[
        ("cat", OneHotEncoder(sparse_output=False), categorical_features)
    ],
    remainder="passthrough"
)

# 划分X和y
X = df[categorical_features + numeric_features]
y = df["delivery_time"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=2025)

# 对特征进行编码
X_train_processed = preprocessor.fit_transform(X_train)
X_test_processed = preprocessor.transform(X_test)

# 5. 建模与预测
model = LinearRegression()
model.fit(X_train_processed, y_train)
y_pred = model.predict(X_test_processed)

# 计算评估指标
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print(f"均方误差（MSE）：{mse:.2f}")
print(f"决定系数（R²）：{r2:.2f}")

# 新订单数据预测
new_order = pd.DataFrame({
    "is_peak": ["是"],
    "weather": ["阴"],
    "distance": [2.3],
    "merchant_rating": [4.7],
    "order_amount": [89]
})
new_order_processed = preprocessor.transform(new_order)
pred_time = model.predict(new_order_processed)
print(f"新订单预测配送时长：{pred_time[0]:.2f}分钟")
